package service

import (
	"fabric-explorer/dao"
	"fabric-explorer/entity"
	"fabric-explorer/tools"
	"fmt"

	"github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

//初始化链码数据
func InitChaincode() {
	contextClient, sdk, err := tools.GetContextClient()
	if err != nil {
		fmt.Print(err)
		return
	}
	defer sdk.Close()

	committedCCList, _ := contextClient.LifecycleQueryCommittedCC(tools.ChannelID, resmgmt.LifecycleQueryCommittedCCRequest{})
	for _, cc := range committedCCList {
		chaincode := entity.Chaincode{
			Name:     cc.Name,
			Sequence: cc.Sequence,
			Version:  cc.Version,
		}
		dao.InsertChaincode(chaincode)
	}
}

//插入数据
func InsertChaincode(chaincode entity.Chaincode) {
	dao.InsertChaincode(chaincode)
}

//获得所有的Chaincode
func GetAllChaincode() []entity.Chaincode {
	return dao.FindChaincodeList(bson.D{})
}

//查询Chaincode的page
func FindChaincodeListPage(selecter bson.D, options *options.FindOptions) []entity.Chaincode {
	return dao.FindChaincodeListPage(selecter, options)
}

//获得所有的Chaincode的数量
func GetChaincodekNum(selecter bson.D) int64 {
	return dao.GetChaincodeNum(selecter)
}

//删除所有的Chaincode数据
func DeleteAllChaincode() {
	dao.DeleteChaincode(bson.D{})
}
